package helper

import (
	"crypto/tls"
	"fmt"
	"log"
	"math/rand"
	"net/smtp"
	"strconv"
	"time"

	"github.com/jordan-wright/email"
)

// 发送验证码
func SendCode(toUserEmail, code string) error {
	e := email.NewEmail()

	e.From = "1690544550@qq.com"
	e.To = []string{toUserEmail}
	e.Subject = "Your validate code"
	e.HTML = []byte(`
	<!DOCTYPE html>
	<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <title>Verification Code</title>
	</head>
	<body>
	    <h1>Go-Im | 你的验证码为: ` + code + `</h1>
	</body>
	</html>
	`)

	// 设置 TLS 配置
	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "smtp.qq.com",
	}

	// 构造 SMTP 服务器地址
	smtpAddr := fmt.Sprintf("%s:%d", "smtp.qq.com", 465)

	// 发送邮件
	err := e.SendWithTLS(smtpAddr, smtp.PlainAuth("", "1690544550@qq.com", "znxogkkkexpbeeaj", "smtp.qq.com"), tlsConfig)
	if err != nil {
		// just ignore it
		log.Println("Failed to send email: ", err)
		// bug 不返回错误，继续执行后续逻辑
		return nil
	}

	return nil
}

// Gen code
func GenCode() string {
	rand.New(rand.NewSource(time.Now().UnixNano()))
	res := ""
	for i := 0; i < 6; i++ {
		res += strconv.Itoa(rand.Intn(10))
	}
	return res
}
